define([
  'text!./search_widget.html',
  '../../assets/vendor/oniui/validation/avalon.validation'
  ], function (sourceHTML) {

  var widget = avalon.ui.searchWidget = function(element, data, vmodels){
  	
    var validationVM;
   
    function showError(el, data) {
        var next = el.nextSibling
        if (!(next && next.className === "error-tip")) {
            next = document.createElement("div")
            next.className = "error-tip"
            el.parentNode.appendChild(next)
        }
        next.innerHTML = data.getMessage()
    }
    function removeError(el) {
        var next = el.nextSibling
        if (next && next.className === "error-tip") {
            el.parentNode.removeChild(next)
        }
    }




    var vmodel = avalon.define(data.searchWidgetId, function(vm){

      // key
      // sort orderby
      
      vm.searchKeyWord = "";
      vm.id = "searchInput"+(new Date()-0);
      _.merge(vm, data.searchWidgetOptions);

      vm.reset = function(){
        validationVM && validationVM.resetAll()
      }
      vm.validation = {
        //@TODO autocomplete.
        onInit: function(v){
          validationVM = v 
        },
        onSuccess: function() {
            // avalon(this).removeClass("error").addClass("success")
            // removeError(this)
        },
        onValidateAll: function(reasons) {
          vm.$fire("all!searchKeyWord",$("#"+vm.id).val())
        }
      }
      vm.$skipArray = ["validation"];

      vm.$init = function(){

        element.innerHTML = sourceHTML;

        avalon.scan(element, [vmodel].concat(vmodels));

      }

      vm.$remove = function(){
        element.innerHtml = element.textContent = "";
      }
     
    }); 

    return vmodel;
  }
  return avalon;
})
